import Vue from 'vue'
import toast from './Toast'

const toastContructor = Vue.extend(toast)

let instance = null

const defaults = {
  duration: 2000,
  content: ''
}

let initToast = () => {
  if (instance) {
    instance.content = ''
  }
}

let getInstance = () => {
  if (!instance) {
    instance = new toastContructor({
      el: document.createElement('div')
    })
  }
  initToast()
  return instance
}

let Toast = (options) => {
  let instance = getInstance()

  if (typeof options === 'undefined') return;
  if (typeof options === 'string') {
    options = {
      content: options
    }
  }
  if (typeof options !== 'object') return;

  options = Object.assign(defaults, options)

  clearTimeout(instance.timer);
  instance.content = options.content

  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    instance.show()
  })
  instance.timer = setTimeout(() => {
    instance.hide()
  }, options.duration)
}

export default Toast